package apps;

import java.util.ArrayList;
import java.util.List;

public class ConnectionPool {

    public List<Connection> connections = createConnections();

    public List createConnections() {
        List<Connection> conn = new ArrayList<Connection>();
        for (int i = 0; i < 5; i++) {
            conn.add(new Connection());
        }
        return conn;
    }

    public Connection getConnection() throws InterruptedException {
        synchronized (connections) {
            while (connections.isEmpty()) {
                connections.wait();
            }
            return connections.remove(0);
        }
    }

    public void returnConnection(Connection con) {
        synchronized (connections) {
            connections.add(con);
            connections.notify();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ConnectionPool cp = new ConnectionPool();
        cp.createConnections();

        for (int i = 0; i < 5; i++) {
            Connection conn = cp.getConnection();
        }
        Connection conn = cp.getConnection();
        System.out.println(cp.connections.size());
        cp.returnConnection(conn);
        System.out.println(cp.connections.size());
    }
}

class Connection {

}